<template>
  <div>
    <el-row>
      <el-col :xs="1" :lg="2"></el-col>
      <el-col :xs="22" :lg="20">
        <el-tabs
          style="max-height: 900px; overflow-y: auto; width: 105%"
          type="border-card"
          tabPosition="left"
          ><el-tab-pane label="食谱数据">
            <el-card>
              <div
                style="
                  display: flex;
                  flex-direction: row;
                  width: 100%;
                  height: 100%;
                  justify-content: space-between;
                  flex-wrap: wrap;
                "
              >
                <div class="charts" ref="charts"></div>
                <div class="charts1" ref="charts1"></div>
                <div class="charts2" ref="charts2"></div>
              </div> </el-card
          ></el-tab-pane>
          <el-tab-pane label="食谱管理"
            ><el-card>
              <el-form :inline="true" class="form">
                <el-form-item>
                  <el-button type="primary" size="default" @click="addMeal"
                    >创建食谱</el-button
                  >
                  <el-button
                    type="danger"
                    size="default"
                    @click="deleteSelectMeals"
                    plain
                    >批量删除</el-button
                  ></el-form-item
                >
                <el-form-item label="食谱名:">
                  <el-input
                    placeholder="请你输入搜索食谱名称"
                    v-model="keyword"
                  ></el-input>
                </el-form-item>
                <el-form-item>
                  <el-button
                    type="primary"
                    size="default"
                    :disabled="keyword ? false : true"
                    @click="search"
                    >搜索</el-button
                  >
                  <el-button type="primary" size="default" @click="reset"
                    >重置</el-button
                  >
                </el-form-item>
              </el-form>

              <el-table
                :data="tableData"
                border
                stripe
                style="width: 100%; margin: 10px 0px"
                max-height="700"
                @selection-change="handleSelectionChange"
                lazy
                :load="load"
              >
                <el-table-column type="selection" align="center" width="50" />
                <el-table-column
                  prop="ID"
                  label="ID"
                  width="80"
                  align="center"
                  sortable
                />
                <el-table-column
                  prop="name"
                  label="名称"
                  width="200"
                  align="center"
                />
                <el-table-column
                  prop="type"
                  label="类别"
                  width="100"
                  align="center"
                />
                <el-table-column
                  prop="category"
                  label="功效"
                  width="150"
                  align="center"
                  show-overflow-tooltip="true"
                >
                  <template #="{ row }" style="display: flex; gap: 2px">
                    <el-tag v-for="item in row.category" size="small">{{
                      item
                    }}</el-tag>
                  </template>
                </el-table-column>
                <el-table-column
                  prop="taste"
                  label="口味"
                  width="100"
                  align="center"
                />
                <el-table-column
                  prop="image"
                  label="图片"
                  width="200"
                  align="center"
                  ><template #="{ row }">
                    <img
                      :src="row.image"
                      style="width: 100px; height: 100px"
                    /> </template
                ></el-table-column>
                <el-table-column
                  prop="favNum"
                  label="收藏数"
                  width="100"
                  align="center"
                  sortable
                />
                <el-table-column
                  prop="viewNum"
                  label="浏览数"
                  width="100"
                  align="center"
                  sortable
                />
                <el-table-column
                  prop="date"
                  label="上传时间"
                  width="150"
                  align="center"
                  sortable
                />
                <el-table-column
                  prop="operation"
                  label="操作"
                  width="200"
                  align="center"
                  style="overflow: hidden"
                >
                  <template #="{ row }">
                    <el-button
                      type="primary"
                      size="small"
                      icon="Edit"
                      @click="updateMeal(row)"
                      >编辑</el-button
                    >
                    <el-popconfirm
                      :title="`你确定要删除${row.name}?`"
                      width="260px"
                      @confirm="deleteMeal(row.ID)"
                    >
                      <template #reference>
                        <el-button type="danger" size="small" icon="Delete"
                          >删除</el-button
                        >
                      </template>
                    </el-popconfirm>
                  </template>
                </el-table-column>
              </el-table>
              <el-pagination
                style="margin-top: 15px"
                v-model:current-page="currentPage"
                v-model:page-size="pageSize"
                :page-sizes="[5, 7, 10, 12, 20]"
                layout="prev, pager, next, jumper,->,sizes,total"
                :total="total"
                @size-change="handleSizeChange"
                @current-change="handleCurrentChange"
              /> </el-card
          ></el-tab-pane>
        </el-tabs>
      </el-col>
      <el-col :xs="1" :lg="2"></el-col>
    </el-row>
    <el-dialog v-model="isCreate" title="创建食谱" width="60%" center>
      <el-form
        :model="newMeal"
        label-width="120px"
        :label-position="left"
        style="width: 80%; margin-left: 5%"
      >
        <el-form-item label="名称">
          <el-input v-model="newMeal.name" placeholder="请输入名称" />
        </el-form-item>
        <el-form-item label="图片">
          <el-upload
            class="avatar-uploader"
            :http-request="httpRequest"
            :show-file-list="false"
            :on-success="handleAvatarSuccess"
            :before-upload="beforeAvatarUpload"
            name="image"
          >
            <img v-if="newMeal.image" :src="newMeal.image" class="avatar" />
            <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
          </el-upload>
        </el-form-item>
        <el-form-item label="口味">
          <el-select
            v-model="newMeal.taste"
            clearable
            placeholder="请选择口味"
            style="width: 240px"
          >
            <el-option
              v-for="item in tasteList"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="种类">
          <el-select
            v-model="newMeal.type"
            clearable
            placeholder="请选择种类"
            style="width: 240px"
          >
            <el-option
              v-for="item in typeList"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="功效">
          <el-select
            v-model="newMeal.category"
            multiple
            filterable
            allow-create
            default-first-option
            :reserve-keyword="false"
            placeholder="选择或新建功效"
            style="width: 240px"
          >
            <el-option
              v-for="item in categoryList"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="制作方法">
          <el-select
            v-model="newMeal.Main_Technique"
            clearable
            placeholder="选择制作方法"
            style="width: 240px"
          >
            <el-option
              v-for="item in TechniqueList"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item
          :label="`食材${index + 1}`"
          v-for="(item, index) in ingredientList"
          :key="index"
        >
          <el-input
            style="width: 240px; margin-right: 10px"
            v-model="item.name"
            placeholder="输入食材名"
          ></el-input>
          <el-input
            style="width: 240px; margin-right: 10px"
            v-model="item.quantity"
            placeholder="输入食材量"
          ></el-input>
          <el-button
            v-if="index !== ingredientList.length - 1"
            @click="removeFormItem(index)"
            type="danger"
            icon="Delete"
            size="small"
            circle
          ></el-button>
          <el-button
            v-else
            round
            :icon="Plus"
            size="small"
            circle
            @click="addIngredient"
          ></el-button>
        </el-form-item>
        <el-form-item label="脂肪含量(g)">
          <el-input-number v-model="newMeal.Fat" :precision="2" :step="0.01"
            ><template #suffix> 岁 </template></el-input-number
          >
        </el-form-item>
        <el-form-item label="蛋白质(g)">
          <el-input-number
            v-model="newMeal.Protein"
            :precision="2"
            :step="0.01"
          />
        </el-form-item>
        <el-form-item label="碳水化合物(g)">
          <el-input-number
            v-model="newMeal.Carbohydrates"
            :precision="2"
            :step="0.01"
          />
        </el-form-item>
        <el-form-item label="纤维(g)">
          <el-input-number
            v-model="newMeal.Fiber"
            :precision="2"
            :step="0.01"
          />
        </el-form-item>
        <el-form-item label="能量(大卡)">
          <el-input-number
            v-model="newMeal.Calories"
            :precision="2"
            :step="0.01"
          />
        </el-form-item>
        <el-form-item label="制作时长">
          <el-select
            v-model="newMeal.Cooking_Time"
            clearable
            placeholder="时长"
            style="width: 240px"
          >
            <el-option
              v-for="item in cookTime"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item
          :label="`制作步骤${index + 1}`"
          v-for="(item, index) in methodList"
          :key="index"
        >
          <el-input
            style="width: 240px; margin-right: 10px"
            placeholder="输入步骤"
            v-model="item.val"
          ></el-input>
          <el-button
            v-if="index !== methodList.length - 1"
            @click="removeMethod(index)"
            type="danger"
            icon="Delete"
            size="small"
            circle
          ></el-button>
          <el-button
            v-else
            @click="addMethod"
            round
            :icon="Plus"
            size="small"
            circle
          ></el-button>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="cancel">取消</el-button>
          <el-button type="primary" @click="handleCreate"> 确定 </el-button>
        </span>
      </template>
    </el-dialog>
    <el-dialog v-model="isEdit" title="编辑与查看" width="80%" center>
      <el-form
        :model="newMeal"
        label-width="100px"
        :label-position="left"
        style="width: 80%; margin-left: 5%"
      >
        <div class="form-top">
          <div class="form-top--left">
            <el-form-item label="名称">
              <el-input v-model="newMeal.Dish_name" placeholder="请输入名称" />
            </el-form-item>
            <el-form-item label="图片">
              <el-upload
                class="avatar-uploader"
                :http-request="httpRequest"
                :show-file-list="false"
                :on-success="handleAvatarSuccess"
                :before-upload="beforeAvatarUpload"
                name="image"
              >
                <img v-if="newMeal.image" :src="newMeal.image" class="avatar" />
                <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
              </el-upload>
            </el-form-item>
            <el-form-item label="口味">
              <el-select
                v-model="newMeal.Taste"
                clearable
                placeholder="请选择口味"
                style="width: 240px"
              >
                <el-option
                  v-for="item in tasteList"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select>
            </el-form-item>
            <el-form-item label="种类">
              <el-select
                v-model="newMeal.meal_type"
                clearable
                placeholder="请选择种类"
                style="width: 240px"
              >
                <el-option
                  v-for="item in typeList"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select>
            </el-form-item>
            <el-form-item label="功效">
              <el-select
                v-model="newMeal.category"
                multiple
                filterable
                allow-create
                default-first-option
                :reserve-keyword="false"
                placeholder="选择或新建功效"
                style="width: 240px"
              >
                <el-option
                  v-for="item in categoryList"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select>
            </el-form-item>

            <el-form-item label="制作方法">
              <el-select
                v-model="newMeal.Main_Technique"
                clearable
                placeholder="选择制作方法"
                style="width: 240px"
              >
                <el-option
                  v-for="item in TechniqueList"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select>
            </el-form-item>
            <el-form-item
              :label="`食材${index + 1}`"
              v-for="(item, index) in ingredientList"
              :key="index"
            >
              <el-input
                style="width: 240px; margin-right: 10px"
                v-model="item.name"
                placeholder="输入食材名"
              ></el-input>
              <el-input
                style="width: 240px; margin-right: 10px"
                v-model="item.quantity"
                placeholder="输入食材量"
              ></el-input>
              <el-button
                v-if="index !== ingredientList.length - 1"
                @click="removeFormItem(index)"
                type="danger"
                icon="Delete"
                size="small"
                circle
              ></el-button>
              <el-button
                v-else
                round
                :icon="Plus"
                size="small"
                circle
                @click="addIngredient"
              ></el-button>
            </el-form-item>
          </div>
          <div class="form-top--right">
            <el-form-item label="脂肪含量(g)">
              <el-input-number
                v-model="newMeal.Fat_y"
                :precision="2"
                :step="0.01"
                ><template #suffix> 岁 </template></el-input-number
              >
            </el-form-item>
            <el-form-item label="蛋白质(g)">
              <el-input-number
                v-model="newMeal.Protein_y"
                :precision="2"
                :step="0.01"
              />
            </el-form-item>
            <el-form-item label="碳水化合物(g)">
              <el-input-number
                v-model="newMeal.Carbohydrates_y"
                :precision="2"
                :step="0.01"
              />
            </el-form-item>
            <el-form-item label="纤维(g)">
              <el-input-number
                v-model="newMeal.Fiber_y"
                :precision="2"
                :step="0.01"
              />
            </el-form-item>
            <el-form-item label="能量(大卡)">
              <el-input-number
                v-model="newMeal.Calories"
                :precision="2"
                :step="0.01"
              />
            </el-form-item>
            <el-form-item label="制作时长">
              <el-select
                v-model="newMeal.Cooking_Time"
                clearable
                placeholder="时长"
                style="width: 240px"
              >
                <el-option
                  v-for="item in cookTime"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select>
            </el-form-item>
            <el-form-item
              :label="`制作步骤${index + 1}`"
              v-for="(item, index) in methodList"
              :key="index"
            >
              <el-input
                style="width: 240px; margin-right: 10px"
                placeholder="输入步骤"
                v-model="item.val"
              ></el-input>
              <el-button
                v-if="index !== methodList.length - 1"
                @click="removeMethod(index)"
                type="danger"
                icon="Delete"
                size="small"
                circle
              ></el-button>
              <el-button
                v-else
                @click="addMethod"
                round
                :icon="Plus"
                size="small"
                circle
              ></el-button>
            </el-form-item>
          </div>
        </div>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="cancelUpdate">取消</el-button>
          <el-button type="primary" @click="handleUpdate"> 确定 </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { onMounted, ref, reactive } from "vue";
import {
  reqAllMeals,
  reqViewTop,
  reqTypePercentage,
  reqFavTenTop,
  reqDeleteMeal,
  reqAddMeal,
  reqDeleteMeals,
  reqDetail,
} from "../../api/menu";
import * as echarts from "echarts";
import { ElMessage } from "element-plus";
import { Plus } from "@element-plus/icons-vue";
let charts = ref();
let charts1 = ref();
let charts2 = ref();
const reqUrl = ref("");
const tableData = ref([]);
const currentPage = ref(1);
const pageSize = ref(5);
const total = ref();
const idList = ref([]);
const keyword = ref("");
const load = ref(false);
const newMeal = ref({});
const isCreate = ref(false);
const isEdit = ref(false);
const tasteList = [
  { value: "家常味", label: "家常味" },
  { value: "咸鲜味", label: "咸鲜味" },
  { value: "甜味", label: "甜味" },
  { value: "香辣味", label: "香辣味" },
  { value: "其他", label: "其他" },
];
const typeList = [
  { value: "breakfast", label: "早餐" },
  { value: "lunch", label: "午餐" },
  { value: "dinner", label: "晚餐" },
];
const categoryList = [
  { value: "助消化", label: "助消化" },
  { value: "补肾", label: "补肾" },
  { value: "补血", label: "补血" },
  { value: "养胃", label: "养胃" },
];
const TechniqueList = [
  { value: "蒸", label: "蒸" },
  { value: "炒", label: "炒" },
  { value: "煮", label: "煮" },
  { value: "炸", label: "炸" },
];
const cookTime = [
  { value: "<15分钟", label: "<15分钟" },
  { value: "<30分钟", label: "<30分钟" },
  { value: "<60分钟", label: "<60分钟" },
  { value: "<2小时", label: "<2小时" },
  { value: ">2小时", label: ">2小时" },
];
const ingredientList = ref([{ name: "", quantity: "" }]);
const methodList = ref([{ val: "" }]);
onMounted(async () => {
  await getAllMeals();
  await getViewTop();
  await getPie();
  await getsScatter();
  await initEchart();
  await initEchart1();
  await initEchart2();
});
const updateMeal = async (row) => {
  let res = await reqDetail(row.ID);
  res.data.category = JSON.parse(res.data.category);
  const rawIngredients = JSON.parse(res.data.Ingredients);
  // 将转换后的数组内容填充到 ingredientList 中
  rawIngredients.forEach((item) => {
    const [name, quantity] = item.split(":");
    ingredientList.value.push({ name: name.trim(), quantity: quantity.trim() });
  });
  ingredientList.value.shift();
  const list = JSON.parse(res.data.Method);
  list.forEach((item) => {
    methodList.value.push({ val: item });
  });
  methodList.value.shift();
  console.log(methodList.value);
  newMeal.value = res.data;
  isEdit.value = true;
};
const cancelUpdate = () => {
  isEdit.value = false;
  newMeal.value = {};
  methodList.value = [{ val: "" }];
  ingredientList.value = [{ name: "", quantity: "" }];
};
const handleUpdate = () => {
  isEdit.value = false;
  newMeal.value = {};
  methodList.value = [{ val: "" }];
  ingredientList.value = [{ name: "", quantity: "" }];
};
const addIngredient = () => {
  ingredientList.value.push({ name: "", quantity: "" });
};
const addMethod = () => {
  methodList.value.push({ val: "" });
};
const removeMethod = (index) => {
  methodList.value.splice(index, 1);
};
const removeFormItem = (index) => {
  ingredientList.value.splice(index, 1);
};
const handleSelectionChange = (val) => {
  let list = [];
  console.log(val);
  val.forEach((item) => {
    list.push(item.ID);
  });
  idList.value = list;
};
const httpRequest = (option) => {
  // newMeal.value.image = window.URL.createObjectURL(option.file);
  const reader = new FileReader();
  reader.readAsDataURL(option.file);
  reader.onload = () => {
    // 将文件转换为 base64 字符串
    newMeal.value.image = reader.result;
  };
  console.log(newMeal.value.image);
};
const handleAvatarSuccess = (response, uploadFile) => {
  newMeal.value.image = window.URL.createObjectURL(uploadFile.raw);
  console.log(newMeal.value.image);
};

const beforeAvatarUpload = (file) => {
  const isJPG = file.type === "image/jpeg";
  const isLt2M = file.size / 1024 / 1024 < 2;
  if (!isJPG) {
    ElMessage.error("头像图片必须是JPG格式!");
    return false;
  } else if (!isLt2M) {
    ElMessage.error("头像图片大小需小于2MB!");
    return false;
  }
  return true;
};
const getAllMeals = async () => {
  const res = await reqAllMeals({
    page: currentPage.value,
    limit: pageSize.value,
    sort_field: "add_time",
    sort_direction: "desc",
    name: keyword.value,
    type: "all",
  });
  tableData.value = res.data;
  console.log(tableData.value);
  for (let i = 0; i < res.data.length; i++) {
    tableData.value[i].category = eval("(" + res.data[i].category + ")");

    switch (res.data[i].type) {
      case "breakfast":
        tableData.value[i].type = "早餐";
        break;
      case "lunch":
        tableData.value[i].type = "午餐";
        break;
      case "dinner":
        tableData.value[i].type = "晚餐";
        break;
    }
  }
  console.log(tableData.value);
  total.value = res.total;
};
const handleSizeChange = async () => {
  await getAllMeals();
};
const handleCurrentChange = async () => {
  await getAllMeals();
};
const deleteSelectMeals = async () => {
  if (idList.value.length == 0) {
    ElMessage.error("请选择要删除的菜品！");
  } else {
    try {
      let res = await reqDeleteMeals({ id_list: idList.value });
      ElMessage.success("删除成功！");
    } catch (e) {
      console.error(e); // 输出错误信息以便调试
      ElMessage.error("删除失败！");
    }
    getAllMeals();
  }
};
const addMeal = async () => {
  isCreate.value = true;
  reqUrl.value = "http://127.0.0.1:8000/addMeal";
};
const handleCreate = async () => {
  newMeal.value.ingredients = JSON.stringify(
    ingredientList.value.map((item) => `${item.name}:${item.quantity}`)
  );
  newMeal.value.method = JSON.stringify(
    methodList.value.map((item) => item.val)
  );
  newMeal.value.category = JSON.stringify(newMeal.value.category);
  let res = await reqAddMeal(newMeal.value);
  if (res.code == 200) {
    ElMessage.success("创建成功！");
  }
  isCreate.value = false;
  getAllMeals();
};
const cancel = async () => {
  isCreate.value = false;
};
const reset = async () => {
  keyword.value = "";
  currentPage.value = 1;
  pageSize.value = 7;
  await getAllMeals();
};
const echartData = ref({
  xdata: [],
  ydata: [],
});
const pieData = ref();
const scatterData = ref([]);
const colorlists = [
  "#6a5acd",
  "#13B5B1",
  "#50F873",
  "#FAD717",
  "#FF6B00",
  "#da70d6",
  "#afeeee",
  "#98db98",
  "#ffc0cb",
  "#0AB2AE",
  "#00ff7f",
  "#708090",
  "#ff4500",
  "#808000",
  "#000080",
  "#20b2aa",
  "#87cefa",
  "#ffa07a",
  "#4b0082",
  "#ffd700",
];
const getViewTop = async () => {
  const res = await reqViewTop();
  echartData.value.xdata = res.data.meal_names;
  echartData.value.ydata = res.data.view_nums;
};
const getPie = async () => {
  const res = await reqTypePercentage();
  pieData.value = res.data;
};
const getsScatter = async () => {
  const res = await reqFavTenTop();
  scatterData.value = res.data;
};
const search = async () => {
  let res = await reqAllMeals({
    name: keyword.value,
    page: currentPage.value,
    limit: pageSize.value,
    sort_field: "add_time",
    sort_direction: "desc",
    type: "all",
  });
  tableData.value = res.data;
  console.log(tableData.value);
  for (let i = 0; i < res.data.length; i++) {
    tableData.value[i].category = eval("(" + res.data[i].category + ")");

    switch (res.data[i].type) {
      case "breakfast":
        tableData.value[i].type = "早餐";
        break;
      case "lunch":
        tableData.value[i].type = "午餐";
        break;
      case "dinner":
        tableData.value[i].type = "晚餐";
        break;
    }
  }
  console.log(tableData.value);
  total.value = res.total;
};
const deleteMeal = async (id) => {
  const res = await reqDeleteMeal(id);
  ElMessage.success("删除成功");
  getAllMeals();
};
const initEchart = () => {
  let mycharts = echarts.init(charts.value);
  let option = {
    title: {
      textStyle: {
        fontSize: 12,
      },
      text: "浏览量柱状图",
      left: "center",
    },
    tooltip: {
      trigger: "axis",
      axisPointer: {
        type: "shadow",
        textStyle: {
          color: "#fff",
        },
      },
    },
    grid: {
      borderWidth: 0,
      top: 30,
      left: 40,
      textStyle: {
        color: "#fff",
      },
    },
    calculable: true,
    xAxis: [
      {
        type: "category",
        name: "食谱名",
        axisLine: {
          lineStyle: {
            width: 2,
          },
          symbol: ["none", "arrow"],
        },
        axisTick: {
          show: false,
        },
        axisLabel: {
          interval: 0,
          textStyle: {
            color: "rgba(0, 0, 0, 0.72)",
            fontSize: 12,
          },
          formatter: function (value) {
            var str = "";
            var num = 5; //每行显示字数
            var valLength = value.length; //该项x轴字数
            var rowNum = Math.ceil(valLength / num); // 行数

            if (rowNum > 1) {
              for (var i = 0; i < rowNum; i++) {
                var temp = "";
                var start = i * num;
                var end = start + num;

                temp = value.substring(start, end) + "\n";
                str += temp;
              }
              return str;
            } else {
              return value;
            }
          },
        },
        splitLine: {
          show: false,
        },
        splitArea: {
          show: true,
          interval: "10%",
        },
        data: echartData.value.xdata,
      },
    ],
    yAxis: [
      {
        type: "value",
        name: "数量",
        axisTick: {
          show: false,
        },
        axisLine: {
          show: true,
          symbol: ["none", "arrow"],
        },
        axisLabel: {
          textStyle: {
            color: "rgba(0, 0, 0, 0.72)",
            fontSize: 15,
          },
          formatter: function (date) {
            return date;
          },
        },
        splitLine: {
          show: true,
          lineStyle: {
            color: "rgba(193, 207, 220, 1)",
            type: "dashed",
          },
        },
      },
    ],
    series: [
      {
        name: "收藏数量",
        type: "bar",
        barMaxWidth: 26,
        width: "100%",
        lef: "-10%",
        itemStyle: {
          normal: {
            color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
              {
                offset: 0,
                color: "rgba(123, 200, 255, 1)",
              },
              {
                offset: 1,
                color: "#359DF5",
              },
            ]),
            label: {
              show: false,
            },
            barBorderRadius: [30, 30, 0, 0], //圆角大小
          },
        },
        data: echartData.value.ydata,
      },
    ],
  };
  mycharts.setOption(option);
};
const initEchart1 = () => {
  let mycharts = echarts.init(charts1.value);
  let option = {
    title: {
      textStyle: {
        fontSize: 12,
      },
      bottom: 5,
      text: "早午晚餐占比",
      left: "center",
    },
    backgroundColor: "#fff",
    tooltip: {
      trigger: "item",
    },
    legend: {
      // orient: 'vertical',
      left: "center",
    },
    series: [
      {
        name: "类别总数",
        type: "pie",
        left: "-5%",
        width: "100%",
        radius: ["50%", "80%"],
        data: pieData.value,
        emphasis: {
          label: {
            show: true,
          },
        },
        itemStyle: {
          borderColor: "#fff",
          borderWidth: 10,
        },
        label: {
          formatter: "{a|{b}}\n{hr|}\n{c|{c}}{u1|个}  {per|{d}}{u2|%}",
          rich: {
            a: {
              color: "#000",
              lineHeight: 25,
              fontSize: 16,
              align: "left",
            },
            hr: {
              borderColor: "#245ECF",
              width: "100%",
              borderWidth: 1,
              height: 0,
              borderType: "dashed",
            },
            c: {
              lineHeight: 40,
              fontSize: 16,
            },
            u1: {
              fontSize: 12,
              lineHeight: 18,
            },
            per: {
              fontSize: 16,
              lineHeight: 40,
            },
            u2: {
              fontSize: 12,
              lineHeight: 18,
            },
          },
        },
        labelLine: {
          length: 0,
          length2: 0,
          lineStyle: {
            // type: 'dashed',
            width: 2,
            // color:'transparent'
          },
        },
      },
    ],
  };
  mycharts.setOption(option);
};
const initEchart2 = () => {
  let mycharts = echarts.init(charts2.value);
  let option = {
    title: {
      textStyle: {
        color: "#1e90ff",
      },
      text: "食谱收藏榜",
      left: "center",
    },
    tooltip: {
      show: "true",
      trigger: "item",
      axisPointer: {
        // 坐标轴指示器，坐标轴触发有效
        type: "shadow", // 默认为直线，可选为：'line' | 'shadow'
      },
    },
    grid: {
      top: "50px",
      bottom: "1px",
      left: "5px",
    },
    xAxis: {
      type: "value",
      show: true,
      axisLine: {
        show: false,
      },
      axisTick: {
        show: false,
      },
      axisLabel: {
        show: false,
      },
      splitLine: {
        show: false,
      },
    },
    yAxis: [
      {
        type: "category",
        axisLabel: {
          show: true, //让Y轴数据不显示
          color: "#00C5CD",
          formatter: function (value) {
            //富文本固定格式{colorName|这里填你想要写的内容}
            //return value <= 3 ? '{start2|' + value + '}' : '{start1|' + value + '}';
            // return value;
          },
          fontSize: 1,
          // padding: [5, 5, 5, 5]
        },
        itemStyle: {},
        axisTick: {
          show: false, //隐藏Y轴刻度
        },
        axisLine: {
          show: false, //隐藏Y轴线段
        },

        data: [],
      },
    ],
    series: [
      {
        color: colorlists,
        type: "scatter",
        symbolSize: 30,
        width: "100%",
        itemStyle: {
          normal: {
            borderWidth: 2,
            borderColor: "#FFF",
            color: function (params) {
              // var colorList = ['#FF6B00','#E3B6EF','#50F873','#13B5B1','#0AB2AE'];
              var colorList = colorlists;
              return colorList[params.dataIndex];
            },
            formatter: function (params) {
              if (params.value > 0) {
                return params.value;
              } else {
                return "";
              }
            },
            opacity: 1,
          },
        },
      },
      {
        name: "食谱收藏数量",
        type: "bar",
        barWidth: 10,
        silent: false,
        itemStyle: {
          normal: {
            barBorderRadius: scatterData.value.length,
            color: function (params) {
              var colorList = colorlists;
              return colorList[params.dataIndex];
            },
          },
        },
        label: {
          normal: {
            show: true,
            position: [0, "-200%"],
            textStyle: {
              color: "#000",
            },
            formatter: function (params) {
              //富文本固定格式{colorName|这里填你想要写的内容}
              var index = params.dataIndex;
              return (
                "NO." +
                (scatterData.value.length - index) +
                " " +
                scatterData.value[index].name
              );
            },
          },
        },
        data: scatterData.value,
      },
    ],
  };
  mycharts.setOption(option);
};
</script>

<style lang="scss" scoped>
.charts {
  width: 800px;
  height: 400px;
}
.charts1 {
  width: 550px;
  height: 400px;
}
.charts2 {
  width: 600px;
  height: 600px;
}
.form-top {
  display: flex;
  justify-content: space-between;
  .form-top--right {
    flex: 1;
  }
}
.form-bottom {
  display: flex;
  justify-content: flex-end;
}
</style>
